package com.thinkfit.jy.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.net.NetworkInfo;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.common.lib.activity.BaseActivity;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.mvp.contract.EmptyContract;
import com.common.lib.mvp.presenter.EmptyPresenter;
import com.thinkfit.jy.R;
import com.thinkfit.jy.bluetooth.Bluetooth;
import com.thinkfit.jy.fragment.AboutSettingFragment;
import com.thinkfit.jy.fragment.AdminModeFragment;
import com.thinkfit.jy.fragment.BrandInfoFragment;
import com.thinkfit.jy.fragment.DeviceInfoFragment;
import com.thinkfit.jy.fragment.GeneralSettingFragment;
import com.thinkfit.jy.fragment.HeartRateListFragment;
import com.thinkfit.jy.fragment.SystemSettingFragment;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.ShowSpeedViewUtils;
import com.thinkfit.jy.utils.SimpleSettingViewUtils;
import com.thinkfit.jy.utils.SportsStatusBarViewUtils;
import com.thinkfit.jy.utils.ThemeUtils;
import com.thinkfit.jy.utils.Utils;
import com.thinkfit.jy.utils.WifiSupport;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 设置界面
 */
public class SettingNewActivity extends BaseActivity<EmptyContract.Presenter> implements EmptyContract.View {

    TextView tvSystemSet,tvGeneralSet,tvAdminMode,tvAbout,tvArea,tvLanguage,tvUnit;
    ViewPager viewPager;
    ConstraintLayout clMain;
    int mCurrentItem;
    private ArrayList<BaseFragment> mFragments;
    private ArrayList<TextView> textViews;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_set_new;
    }

    @Override
    protected void onCreated(@Nullable Bundle savedInstanceState) {
        mCurrentItem = getIntent().getIntExtra(Constants.BUNDLE_EXTRA, 0);
        setViewsOnClickListener(R.id.ll_sport_back,R.id.cl_set_item,R.id.tv_system_set,R.id.tv_general_set,R.id.tv_admin_mode,R.id.tv_about);
        clMain = findViewById(R.id.cl_main);
        tvSystemSet = findViewById(R.id.tv_system_set);
        tvGeneralSet = findViewById(R.id.tv_general_set);
        tvAdminMode = findViewById(R.id.tv_admin_mode);
        tvAbout = findViewById(R.id.tv_about);
        viewPager = findViewById(R.id.viewPager);
        tvArea = findViewById(R.id.tv_area);
        tvLanguage = findViewById(R.id.tv_language);
        tvUnit = findViewById(R.id.tv_unit);

//        mCurrentItem = 0;
        textViews = new ArrayList<>();
        textViews.add(tvSystemSet);
        textViews.add(tvGeneralSet);
        textViews.add(tvAdminMode);
        textViews.add(tvAbout);

        mFragments = new ArrayList<>();
        mFragments.add(SystemSettingFragment.getInstance(0));
        mFragments.add(GeneralSettingFragment.getInstance(1));
//        mFragments.add(AdminModeFragment.getInstance(2));
        mFragments.add(HeartRateListFragment.getInstance(2));
        mFragments.add(AboutSettingFragment.getInstance(3));

        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }

        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mCurrentItem = position;
                resetBtn();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
//        viewPager.setCurrentItem(mCurrentItem);
        toFragment(mFragments.get(mCurrentItem));
        resetBtn();
        Utils.initRegion(tvArea,tvLanguage,tvUnit);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            setImage(R.id.iv_wifi, WifiSupport.isWifiConnected(getContext()) ? R.drawable.img_main_wifi:
                    R.drawable.img_main_wifi_back);
        }catch (Exception e){
            e.printStackTrace();
        }
        showBottomUI();
        SportsStatusBarViewUtils.getInstance().isMain(false);
        ShowSpeedViewUtils.getInstance().goneLayout();
        clMain.setBackgroundResource(ThemeUtils.getInstance().getMainTheme());
        initSound();
    }

    @NonNull
    @Override
    protected EmptyContract.Presenter onCreatePresenter() {
        return new EmptyPresenter(this);
    }

    @Override
    public void onReceive(@NonNull HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        if (map.containsKey(EventBusEvent.BLUETOOTH_SUCCESS)) {
            finish();
        }if (map.containsKey(EventBusEvent.BLUETOOTH_CHANGE)) {
//            showBottomUI();
            boolean b = (boolean) map.get(EventBusEvent.BLUETOOTH_CHANGE);
            if(b){
                setImage(R.id.iv_bluetooth,R.drawable.img_main_bluetooth);
            }else {
                setImage(R.id.iv_bluetooth, R.drawable.img_main_bluetooth_back);
            }
        }else if(map.containsKey(EventBusEvent.VOICE_CHANGE)){
            int i = (int) map.get(EventBusEvent.VOICE_CHANGE);
            if(i <= 0){
                setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_off);

            }else {
                setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_max);
            }
//            SportsStatusBarViewUtils.getInstance().setVolume((int) map.get(EventBusEvent.VOICE_CHANGE));
        }else if (map.containsKey(EventBusEvent.REFRESH_WIFI)) {
            //TODO 临时try，界面来不及统一
            try {
                setImage(R.id.iv_wifi, WifiSupport.isWifiConnected(getContext()) ? R.drawable.img_main_wifi:
                        R.drawable.img_main_wifi_back);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(map.containsKey(EventBusEvent.WIFI_CHANGE)){
            boolean b = (boolean) map.get(EventBusEvent.WIFI_CHANGE);
            if(!b){
                setImage(R.id.iv_wifi, R.drawable.img_main_wifi_back);
            }
        }else if(map.containsKey(EventBusEvent.TO_FRAGMENT)){
            int item = (int) map.get(EventBusEvent.TO_FRAGMENT);
            if(item<=3){
                mCurrentItem = item;
                toFragment(mFragments.get(mCurrentItem));
                resetBtn();
            }else if(item == 4){
                toFragment(new DeviceInfoFragment());
            }else if(item == 5){
                toFragment(new BrandInfoFragment());
            }
        } else {
            super.onReceive(map);
        }
    }

    public void showBottomUI(){
        if(Bluetooth.getInstance().isBluetoothOpened()){
            setImage(R.id.iv_bluetooth, BluetoothOrder.getInstance().isConnect() ?
                    R.drawable.img_main_bluetooth_connect : R.drawable.img_main_bluetooth);
        }else {
            setImage(R.id.iv_bluetooth, R.drawable.img_main_bluetooth_back);
        }
    }

    public void setWifiImag(boolean isWifiConnected) {
        if (isWifiConnected){
            setImage(R.id.iv_wifi,R.drawable.img_main_wifi);
        }else {
            setImage(R.id.iv_wifi,R.drawable.img_main_wifi_back);
        }
    }
    public void initSound(){
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        if(currentVolume <= 0){
            setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_off);

        }else {
            setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_max);
        }
    }


    private void resetBtn() {
        for (int i = 0; i < textViews.size(); ++i) {
            if (i == mCurrentItem) {
                textViews.get(i).setBackgroundResource(R.drawable.img_set_item_bg);
                textViews.get(i).setTypeface(null, Typeface.BOLD);
                textViews.get(i).setTextColor(ContextCompat.getColor(this, com.common.lib.R.color.text_color_1));
            } else {
                textViews.get(i).setBackgroundResource(android.R.color.transparent);
                textViews.get(i).setTypeface(null, Typeface.NORMAL);
                textViews.get(i).setTextColor(ContextCompat.getColor(this, com.common.lib.R.color.text_color_1));
            }
        }
    }

    public void toFragment(Fragment fragment) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.anim.slide_fragment_in,R.anim.slide_fragment_out);
        ft.replace(R.id.fl_layout, fragment);
        ft.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_sport_back:
                finish();
                break;
            case R.id.cl_set_item:
//                SimpleSettingViewUtils.getInstance().initView(getContext(),this);
                break;
            case R.id.tv_system_set:
                mCurrentItem = 0;
                toFragment(mFragments.get(mCurrentItem));
                resetBtn();
//                viewPager.setCurrentItem(0);
                break;
            case R.id.tv_general_set:
                mCurrentItem = 1;
                toFragment(mFragments.get(mCurrentItem));
                resetBtn();
//                viewPager.setCurrentItem(1);
                break;
            case R.id.tv_admin_mode:
                mCurrentItem = 2;
                toFragment(mFragments.get(mCurrentItem));
                resetBtn();
//                viewPager.setCurrentItem(2);
                break;
            case R.id.tv_about:
                mCurrentItem = 3;
                toFragment(mFragments.get(mCurrentItem));
                resetBtn();
//                viewPager.setCurrentItem(3);
                break;

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBroadcastReceive(Intent intent) {
        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
            switch (state) {
                case WifiManager.WIFI_STATE_DISABLED: {
                    Log.d(TAG, "已经关闭");
//                    isWifiOpened = false;
                    break;
                }
                case WifiManager.WIFI_STATE_DISABLING: {
                    Log.d(TAG, "正在关闭");
                    break;
                }
                case WifiManager.WIFI_STATE_ENABLED: {
                    Log.d(TAG, "已经打开");
//                    isWifiOpened = true;
//                    sortScaResult();
                    break;
                }
                case WifiManager.WIFI_STATE_ENABLING: {
                    Log.d(TAG, "正在打开");
                    break;
                }
                case WifiManager.WIFI_STATE_UNKNOWN: {
                    Log.d(TAG, "未知状态");
                    break;
                }
            }
        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            if (NetworkInfo.State.DISCONNECTED == info.getState()) {//wifi没连接上
                Log.d(TAG, "wifi没连接上");

            } else if (NetworkInfo.State.CONNECTED == info.getState()) {//wifi连接上了
                Log.d(TAG, "wifi连接上了");
                WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getContext());
                //连接成功 跳转界面 传递ip地址
//                tvWlan.setText(connectedWifiInfo.getSSID().replace("\"", ""));
                setWifiImag(true);
                dismissProgressDialog();
            } else if (NetworkInfo.State.CONNECTING == info.getState()) {//正在连接
                Log.d(TAG, "wifi正在连接");
                WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getContext());

            }
        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
//            isWifiChange = true;
        } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            switch (state) {//TODO Setting文件里面代码，网络状态监听变化 断开、连接、密码错误的操作全在这里进行
                case ASSOCIATING://申请连接中
//                    mWasAssociating = true;
                    break;
                case ASSOCIATED:
//                    mWasAssociated = true;
                    break;
                case COMPLETED://连接成功后进入
//                    isExit = false;
//                    isWifiOpened = false;
                    WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getContext());
                    //连接成功 跳转界面 传递ip地址
//                    tvWlan.setText(connectedWifiInfo.getSSID().replace("\"", ""));
                    setWifiImag(true);
                    dismissProgressDialog();
                    HashMap<String, Object> map = new HashMap<>();
                    map.put(EventBusEvent.REFRESH_WIFI,0);
                    EventBus.getDefault().post(map);
                    break;
                case DISCONNECTED://断开连接后进入dormant判断是密码错误还是其他连接错误
                case DORMANT:
                    setWifiImag(false);
//                    tvWlan.setText(getString(R.string.app_not_connect));
//                    isWifiOpened = false;
//                    if (mWasAssociated || mWasHandshaking) {
//                        if (mConnectType != 0) {
//                            //解绑
//                            mConnectType = 0;
//                            WifiSupport.doDisconnectWifi("\"" + mConnectionWifi.getWifiName() + "\"", getActivity());
//                            sortScaResult();
//                            dismissProgressDialog();
//                            Intent i = new Intent(getActivity(), DialogActivity.class);
//                            i.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.SHOW_INPUT_WIFI_PSW_DIALOG);
//                            i.putExtra(Constants.BUNDLE_EXTRA_2, mConnectionWifi.getWifiName());
//                            mLauncher.launch(i);
//                            showToast(R.string.app_check_wifi_password);
//                        }
//                    }
                    break;
                case INTERFACE_DISABLED:
                case UNINITIALIZED:
                    break;
                case FOUR_WAY_HANDSHAKE://四次握手进入连接
                case GROUP_HANDSHAKE:
//                    mWasHandshaking = true;
                    break;
            }
        }
    }

}